package com.qdu.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.qdu.commons.RedisKey;
import com.qdu.commons.Result;
import com.qdu.entity.RouteTrace;
import com.qdu.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class RedisStartupService implements InitializingBean {

    @Autowired
    IRouteTraceService routeTraceService;

    @Autowired
    IUserService userService;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void afterPropertiesSet() throws Exception {
      log.info("==================Redis缓存预热================");
      this.init();
    }

    private void init() {
        Set keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        this.initRouteTrace();
        this.initAllUserInfo();
    }

    public  void initRouteTrace() {
        log.info("==================Redis路线信息预热================");
        //
        List<RouteTrace> routeTraces  = routeTraceService.list();
        if (routeTraces.size()==0){
            log.error("路线信息预热失败！！！");
        }
        Map<Integer,List<RouteTrace>>routesMap=routeTraces.parallelStream().collect(Collectors.groupingBy(RouteTrace::getRouteId));

        for (Integer routeId : routesMap.keySet()){
            redisTemplate.opsForList().rightPushAll(RedisKey.ROUTE_TRACE+routeId, routesMap.getOrDefault(routeId, null));
        }
    }

    public  void initAllUserInfo() {
        log.info("==================Redis用户信息预热================");
        //
        List<User> users = userService.list();
        LinkedHashMap<Integer,User> usersMap= new LinkedHashMap<>();
        for (User user : users) {
            usersMap.put(user.getId(), user);
            redisTemplate.opsForZSet().incrementScore(RedisKey.RANK, user.getId(), user.getPoint());
            redisTemplate.opsForHash().put(RedisKey.ALL_USER_INFO, user.getId().toString(), user);
        }
    }
}
